package com.shell.governor.authorization.rx;

import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.governor.authorization.UserRoleEvent;
import com.shell.governor.authorization.po.PubRole;
import com.shell.governor.authorization.service.PubRoleService;
import com.shell.governor.modules.message.keyword.SmsAuthOptKeyword;
import com.shell.governor.user.po.PubUser;
import com.shell.governor.user.po.PubUserRole;
import com.shell.governor.user.service.PubUserService;
import com.shell.properties.GovernorProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthRoleMsgSubscriber extends OnErrorNotImplementedSubscriber<UserRoleEvent> {
	@Autowired
	private PubUserService pubUserService;
	@Autowired
	PubRoleService roleService;
	@Autowired
	private GovernorProperties governorProperties;

	public void onApplicationEvent(UserRoleEvent userRoleEvent) {
		PubUserRole userRole = userRoleEvent.getPubUserRole();
		if (userRole != null) {
			PubUser user = (PubUser) this.pubUserService.selectByKey(userRole.getUserId());
			PubRole role = (PubRole) this.roleService.selectByKey(userRole.getRoleId());
			String msgTemplate = "";
			if ("ENT_REVIEWER".equals(role.getRoleCode())) {
				msgTemplate = "MT02108";
			} else if ("ENT_OPERATOR".equals(role.getRoleCode())) {
				msgTemplate = "MT02107";
			}
			if ((!StringUtil.emptyAndNull(user.getPhoneNo())) && (!StringUtil.emptyAndNull(msgTemplate))) {
				SmsAuthOptKeyword authKeyword = new SmsAuthOptKeyword();
				authKeyword.setUrl(this.governorProperties.getUrl());
				authKeyword.setUserName(CommonDataUtil.getUserName());
				MessageSender.sendMessageToPhone(user.getPhoneNo(), CommonDataUtil.getUserId(), msgTemplate,
						authKeyword);
			}
		}
	}
}
